import { View, Text, ScrollView } from "@tarojs/components";

import HeaderSearch from "@/components/HeaderSearch/index";
import Header from "@/components/Header/index";
import Footer from "@/components/Footer/index";
import GoodsTitle from "@/components/GoodsTitle/index";
import { useEffect, useRef, useState } from "react";
import {
  Button,
  Image,
  Popup,
  Form,
  Cell,
  Toast,
  Uploader,
  Input,
  Empty,
  Dialog,
} from "@taroify/core";
import { requestPOST } from "@/request";
import { useSelector } from "react-redux";
import { RootState } from "@/store";
import { PhotoFail } from "@taroify/icons";
import Taro from "@tarojs/taro";

export default function Index() {
  const [list, setList] = useState<any>([]);
  const businessId = useSelector(
    (state: RootState) => state.business.businessId
  );
  const [open, setOpen] = useState(false);
  const [form, setForm] = useState({
    id: null,
    image: "",
    name: "",
    email: "",
    domain: "",
    contact: "",
    sort: "",
    isAdd: 2,
  });
  const [files, setFiles] = useState<Uploader.File[]>([]);

  const getList = () => {
    requestPOST(`index/contactUs/${businessId}`).then((res: any) => {
      setList([...res]);
    });
  };

  const onUpload = () => {
    Taro.chooseImage({
      count: 1,
      sizeType: ["original", "compressed"],
      sourceType: ["album", "camera"],
    }).then(({ tempFiles, tempFilePaths }) => {
      Taro.uploadFile({
        url: process.env.TARO_APP_API + "/other/upload",
        filePath: tempFilePaths[0],
        name: "file",
        success(res) {
          setFiles([
            ...tempFiles.map(({ path, type, originalFileObj }) => ({
              type,
              url: path,
              name: originalFileObj?.name,
            })),
          ]);
          const { relativeUrl } = JSON.parse(res.data).data;
          setForm({
            ...form,
            image: relativeUrl,
          });
          Toast.open({ type: "success", message: "上传成功" });
        },
        fail() {
          Toast.open({ type: "fail", message: "upload error" });
        },
      });
    });
  };

  const formRef = useRef<any>();

  const onSubmit = () => {
    if (!form.image) return Toast.open({ type: "fail", message: "请上传头像" });
    requestPOST("shop/editShopContact", { ...form }).then(() => {
      Toast.open({ type: "success", message: "保存成功" });
      setOpen(false);
      setForm({
        id: null,
        image: "",
        name: "",
        email: "",
        domain: "",
        contact: "",
        sort: "",
        isAdd: 2,
      });
      formRef.current?.reset();
      setFiles([]);
      getList();
    });
  };

  const editList = (item) => {
    setForm({ ...item, isAdd: 1 });
    if (item.image) {
      setFiles([{ url: process.env.TARO_APP_API + item.image }]);
    }
    setOpen(true);
  };

  const delList = (item) => {
    Dialog.confirm({
      title: "提示",
      message: "您确定要删除吗？",
      onConfirm() {
        requestPOST(`shop/delShopContact/${item.id}`).then(() => {
          Toast.open({ type: "success", message: "删除成功" });
          getList();
        });
      },
    });
  };

  useEffect(() => {
    getList();
  }, []);

  return (
    <View className="taroBox">
      <HeaderSearch />
      <Header />
      <View>
        <GoodsTitle title="联系方式" isMore={false} />
        <View style={{ padding: "14px 14px 0 14px" }}>
          <Button color="primary" size="small" onClick={() => setOpen(true)}>
            添加
          </Button>
        </View>
        <View
          style={{
            display: "flex",
            flexDirection: "column",
            gap: "20px",
            padding: "14px",
          }}
        >
          {!list.length && (
            <Empty>
              <Empty.Image />
              <Empty.Description>暂无数据</Empty.Description>
            </Empty>
          )}
          {list.map((item) => (
            <View
              key={item.id}
              style={{
                padding: "10px",
                boxShadow: "0 0 .3125rem 0 hsla(0, 0%, 49%, 0.45)",
              }}
            >
              <View
                style={{
                  display: "flex",
                  gap: "10px",
                }}
              >
                <View style={{ width: "102px" }}>
                  <Image
                    src={
                      item.image
                        ? process.env.TARO_APP_API + item.image
                        : "error"
                    }
                    width={102}
                    height="100%"
                    mode="aspectFill"
                    fallback={<PhotoFail />}
                  />
                </View>

                <View
                  style={{
                    fontSize: "14px",
                    display: "flex",
                    flexDirection: "column",
                    gap: "5px",
                  }}
                >
                  <View style={{ fontSize: "16px" }}>{item.name}</View>
                  <View>邮箱：{item.email}</View>
                  <View>域名：{item.domain}</View>
                  <View>联系方式：{item.contact}</View>
                  <View>排序{item.sort}</View>
                </View>
              </View>
              <View
                style={{
                  display: "flex",
                  gap: "20px",
                  alignItems: "center",
                  marginTop: "10px",
                }}
              >
                <Button
                  color="primary"
                  size="small"
                  variant="outlined"
                  onClick={() => editList(item)}
                >
                  修改
                </Button>
                <Button
                  color="danger"
                  size="small"
                  variant="outlined"
                  onClick={() => delList(item)}
                >
                  删除
                </Button>
              </View>
            </View>
          ))}
        </View>
      </View>
      <Footer />

      <Popup
        open={open}
        placement="center"
        style={{ height: "auto" }}
        rounded
        lock={false}
      >
        <ScrollView style={{ maxHeight: "90vh" }} scrollY>
          <View style={{ width: "90vw", padding: "14px 0" }}>
            <Form
              ref={formRef}
              defaultValues={form}
              onSubmit={() => onSubmit()}
            >
              <Cell.Group inset>
                <Form.Item style={{ flexDirection: "column", gap: "10px" }}>
                  <Form.Label style={{ width: "100%" }}>
                    <Text>
                      添加轮播图
                      <Text style={{ fontSize: "12px", color: "red" }}>
                        推荐尺寸1920*670,图片最大不能超过500KB
                      </Text>
                    </Text>
                  </Form.Label>
                  <Form.Control>
                    <Uploader
                      value={files}
                      onUpload={onUpload}
                      onChange={setFiles}
                    ></Uploader>
                  </Form.Control>
                </Form.Item>
                <Form.Item
                  name="name"
                  rules={[{ required: true, message: "请输入姓名" }]}
                >
                  <Form.Label>姓名</Form.Label>
                  <Form.Control>
                    <Input
                      placeholder="姓名"
                      value={form.name}
                      onChange={(e) =>
                        setForm({ ...form, name: e.detail.value })
                      }
                    />
                  </Form.Control>
                </Form.Item>
                <Form.Item
                  name="email"
                  rules={[{ required: true, message: "请输入邮箱" }]}
                >
                  <Form.Label>邮箱</Form.Label>
                  <Form.Control>
                    <Input
                      placeholder="邮箱"
                      value={form.email}
                      onChange={(e) =>
                        setForm({ ...form, email: e.detail.value })
                      }
                    />
                  </Form.Control>
                </Form.Item>
                <Form.Item
                  name="domain"
                  rules={[{ required: true, message: "请输入域名" }]}
                >
                  <Form.Label>域名</Form.Label>
                  <Form.Control>
                    <Input
                      placeholder="域名"
                      value={form.domain}
                      onChange={(e) =>
                        setForm({ ...form, domain: e.detail.value })
                      }
                    />
                  </Form.Control>
                </Form.Item>
                <Form.Item
                  name="contact"
                  rules={[{ required: true, message: "请输入联系方式" }]}
                >
                  <Form.Label>联系方式</Form.Label>
                  <Form.Control>
                    <Input
                      placeholder="联系方式"
                      value={form.contact}
                      onChange={(e) =>
                        setForm({ ...form, contact: e.detail.value })
                      }
                    />
                  </Form.Control>
                </Form.Item>
                <Form.Item name="sort">
                  <Form.Label>排序</Form.Label>
                  <Form.Control>
                    <Input
                      placeholder="排序"
                      value={form.sort}
                      onChange={(e) =>
                        setForm({ ...form, sort: e.detail.value })
                      }
                    />
                  </Form.Control>
                </Form.Item>
              </Cell.Group>
              <View
                style={{
                  margin: "1rem",
                  display: "flex",
                  alignItems: "center",
                  gap: "30px",
                }}
              >
                <Button
                  shape="round"
                  block
                  color="primary"
                  variant="outlined"
                  onClick={() => {
                    setForm({
                      id: null,
                      image: "",
                      name: "",
                      email: "",
                      domain: "",
                      contact: "",
                      sort: "",
                      isAdd: 2,
                    });
                    formRef.current?.reset();
                    setFiles([]);
                    setOpen(false);
                  }}
                >
                  取消
                </Button>
                <Button shape="round" block color="primary" formType="submit">
                  提交
                </Button>
              </View>
            </Form>
          </View>
        </ScrollView>
      </Popup>
    </View>
  );
}
